package com.ruoyi.common.s7.ST30;

import com.alibaba.fastjson2.JSON;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.ruoyi.common.s7.BaseVo;
import com.ruoyi.common.s7.ExchangeIntf;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class ST30Exchange implements ExchangeIntf {
    public  static int areaNumber = 5403;
    public static String ipAddress = "192.168.0.51";
    public static void main(String[] args) {
        ST30Handle sT30Handle =   new ST30Handle();
        S7Connector s7ReadConnector = sT30Handle.initConnect(ipAddress);
        ST30Vo st30Vo = sT30Handle.read(s7ReadConnector, areaNumber);
        if(st30Vo.getNewPnFlag() ==1){
            log.info(JSON.toJSONString(st30Vo));
            try {
                s7ReadConnector.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     *
     * @return
     */
    @Override
    public BaseVo readPLC() {
        ST30Handle sT30Handle =    new ST30Handle();
        S7Connector s7Connector = sT30Handle.initConnect(ipAddress);
        ST30Vo resultVo = sT30Handle.read(s7Connector, areaNumber);
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return resultVo;
    }

    /**
     *
     * @param paramVo
     */
    @Override
    public void writePLC(BaseVo paramVo) {
        ST30Vo st30Vo = (ST30Vo) paramVo;
        ST30Handle sT30Handle =   new ST30Handle();
        S7Connector s7Connector = sT30Handle.initConnect(ipAddress);
        if(st30Vo.getNewPnFlag()==1){
            //写入newPnFlag
            byte[] newPnFlag = new byte[1];
            newPnFlag[0] = 2;
            s7Connector.write(DaveArea.DB, areaNumber, 186, newPnFlag);
            //写入结果
            byte[] result  = new byte[1];
            result[0] = st30Vo.getResult();
            s7Connector.write(DaveArea.DB, areaNumber, 187, result);
        }
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
